//
// Created by xili on 2024/10/10 15:54.
// GO BIG OR GO HOME.
//
#include "leetcode.h"

class Solution {
public:
    long long maxSum(vector<int> &nums, int m, int k) {
        unordered_map<int, int> ump;
        long long sum = 0;
        for (int i = 0; i < k - 1; i++) {
            ump[nums[i]]++;
            sum += nums[i];
        }
        int n = nums.size();
        long long ans = 0;
        for (int i = k - 1; i < n; i++) {
            ump[nums[i]]++;
            sum += nums[i];
            if (ump.size() >= m) {
                ans = max(ans, sum);
            }
            int out = nums[i - k + 1];
            if (!--ump[out]) {
                ump.erase(nums[out]);
            }
            sum -= out;
        }
        return ans;
    }
};